#include <iostream>

#include <memory>

#include "httpServer.hpp"

using namespace std;
using namespace Server;


bool heander(const httpRequest& req, httpResponse& respond)
{
    cout << "-------------------http start----------------------" << endl;
    
    cout << "method: " << req.method << endl;
    cout << "url: " << req.url << endl;
    cout << "version: " << req.version << endl;
    cout << "path: " << req.path << endl;
    cout << endl << req.inbuffer;
    cout << "-------------------http end----------------------" << endl;

    string body;
    if (!Util::readFile(req.path, &body))
    {
        Util::readFile(html_404, &body);
    }
    string respline = "HTTP/1.1 200 OK\r\n";
    string respheader = Util::suffixToDoec(req.suffix);
    string contLenth;
    if (req.lenth >= 0)
    {
        contLenth = "Content-Length: " + to_string(req.lenth) + "\r\n";
    }
    string localtion = "Location: https://www.qq.com/\r\n";
    string cookie = "Set-Cookie: name=1234567abcdefg; Max-Age=120\r\n";
    string respblank = "\r\n";

    respond.outbuffer = respline + respheader + contLenth /*+ localtion*/ + cookie + respblank + body;

    return true;
}

inline void Usage(std::string proc)
{
    std::cout << "Usage : \n\t" << proc << " local_port\n\n";
}

// ./httpServer 8080
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }

    uint16_t port = atoi(argv[1]);

    unique_ptr<httpServer> server(new httpServer(heander, port));
    server->init();
    server->start();

    return 0;
}